<script>
import { searchGlobalSettings, updateAllGlobalSetting } from '@/api/globalSetting'
import codemirror from '@/components/JavascriptCodemirror/index.vue'
import { getToolID, getTools } from '@/api/tool'

export default {
  name: 'NewIndex',
  components: {
    codemirror
  },
  data() {
    return {
      stage: -1, // 大模型阶段
      modelList: [], // 标签列表
      toolList: [], // 工具下拉选择框列表
      nowTool: null, // 当前选择的工具
      nowPrompt: '', // 当前的提示词
      nowParams: '', // 当前的参数
      isHidden: false // 用于三级路由
    }
  },
  watch: {
    'stage'(newVal) {
      this.$nextTick(async() => {
        const api_name = this.modelList[newVal].api
        const prompt_name = this.modelList[newVal].prompt
        const params_name = this.modelList[newVal].parameters
        searchGlobalSettings({ 'searchVal': prompt_name })
          .then((res) => {
            this.nowPrompt = res[0].value
          })
          .catch(err => {
            console.log('切换标签时获取大模型设置出错：', err)
          })
        await searchGlobalSettings({ 'searchVal': api_name })
          .then((res) => {
            if (res[0].value) {
              this.nowTool = null
              this.$nextTick(() => {
                this.nowTool = parseInt(res[0].value)
              })
            } else {
              this.nowTool = null
            }
          })
          .catch(err => {
            console.log('切换标签时获取大模型设置出错：', err)
          })
        searchGlobalSettings({ 'searchVal': params_name })
          .then((res) => {
            // 如果已经设置过，默认显示已经设置的;如果没设置过，则从工具中取
            if (res[0].value !== null) {
              this.nowParams = res[0].value
            } else {
              getToolID(this.nowTool)
                .then(res => {
                  this.nowParams = JSON.stringify(res.parameters, null, 2)
                })
                .catch(err => {
                  console.log('根据工具id获取参数时出错', err)
                })
            }
          })
          .catch(err => {
            console.log('切换标签时获取大模型设置出错：', err)
          })
      })
    },
    'nowTool'(newVal, oldVal) {
      if (newVal !== null && oldVal !== null) {
        this.$confirm(this.$t('model_page_switching_tool_tip'), this.$t('tip'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning',
          closeOnClickModal: false
        }).then(() => {
          getToolID(this.nowTool)
            .then(res => {
              this.nowParams = JSON.stringify(res.parameters, null, 2)
              console.log('---------', res.parameters)
            })
            .catch(err => {
              console.log('根据工具id切换参数时出错', err)
            })
        }).catch(() => {
          this.nowTool = null
          this.$nextTick(() => {
            this.nowTool = oldVal
          })
        })
      }
    }
  },
  created() {
    // 添加权限校验逻辑
    if (!this.$store.getters.isAdmin()) {
      this.$message({
        type: 'error',
        message: '您没有权限访问此页面'
      })
      this.$router.push('/')
      return
    }
    // 初始化，获得编辑面板的值
    this.fetchData()
  },
  methods: {
    fetchData() {
      searchGlobalSettings({ 'searchVal': 'model_setting' })
        .then(res => {
          this.modelList = JSON.parse(res[0].value)
          this.stage = 0
        })
        .catch(err => {
          console.log('获取大模型设置时出错：', err)
        })
      const param = JSON.stringify({ 'page': 1, 'pagesize': 60 })
      getTools(param)
        .then(res => {
          this.toolList = res['tools']
        })
        .catch(err => {
          console.log('获取工具列表时出错：', err)
        })
    },
    saveSetting() {
      /* 构造保存的数据结构 */
      const api_name = this.modelList[this.stage].api
      const prompt_name = this.modelList[this.stage].prompt
      const params_name = this.modelList[this.stage].parameters
      const data = {}
      data[api_name] = this.nowTool
      data[prompt_name] = this.nowPrompt
      data[params_name] = this.nowParams
      /* 保存设置 */
      updateAllGlobalSetting(data)
        .then(() => {
          this.$message({
            message: this.$t('Modified_successfully'),
            type: 'success'
          })
        })
        .catch(err => {
          console.log('保存设置时出错', err)
        })
    },
    paramsChange(newVal) {
      this.nowParams = newVal
    },
    promptChange(newVal) {
      this.nowPrompt = newVal
    }
  }
}
</script>

<template>
  <div>
    <div :class="{ hidden: isHidden }">
      <div class="app-container">
        <!-- 选择阶段 -->
        <div style="margin-bottom: 10px;">
          <el-row type="flex" justify="left" align="middle">
            <el-radio-group v-model="stage">
              <el-radio-button v-for="(model, index) in modelList" :key="index" :label="index">{{ model.label }}</el-radio-button>
            </el-radio-group>
          </el-row>
        </div>

        <!--编辑面板-->
        <div style="background-color: white;padding-top: 40px;">
          <el-form ref="ruleForm" label-width="120px">
            <el-row type="flex" justify="center">
              <el-col :span="23">
                <el-form-item :label="$t('Large_model')">
                  <el-select v-model="nowTool" filterable>
                    <el-option
                      v-for="item in toolList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                      style="width: 100%;"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item :label="$t('parameter')">
                  <codemirror :code_from="nowParams" @codeChange="paramsChange" />
                </el-form-item>
                <el-form-item :label="$t('prompt_word')">
                  <codemirror :code_from="nowPrompt" @codeChange="promptChange" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="saveSetting">{{ $t('save') }}</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
    </div>

    <div :class="{ hidden: !isHidden }">
      <router-view />
    </div>
  </div>
</template>

<style scoped>

</style>
